//Show recently modified files.
//
//UPDATE ME
package main

import (
	"fmt"
	"log"
	"time"
	"flag"
	"os"
	"bufio"
)

//BUG(jmf): uses naive time arithmetic
var (
	v = flag.Bool("v", false, "invert matches")
	z = flag.Bool("0", false,
		"use null separated values when reading from stdin")
	q     = flag.Bool("q", false, "print nothing")
	ctime = flag.Bool("ctime", false, "use ctime instead of mtime")
	min   = flag.Int("m", 0, "minutes")
	hour  = flag.Int("h", 0, "hours")
	day   = flag.Int("d", 0, "days")
	month = flag.Int("M", 0, "months")
	year  = flag.Int64("y", 0, "years")
	delim byte = '\n'
	epoch int64
	seen  bool
)

func Int(kind string, i, max int) int {
	if i < 0 || i > max {
		log.Fatalln(kind + " is invalid")
	}
	return i
}

func recent(name string, follow bool) {
	s, err := os.Stat(name)
	if err != nil {
		if name == "-" {
			if follow {
				read()
			}
		} else {
			log.Println(err)
		}
		return
	}

	tm := s.Mtime_ns
	if *ctime {
		tm = s.Ctime_ns
	}

	d := epoch <= tm/1e12
	if *v {
		d = !d
	}
	if d {
		seen = true
		if !*q {
			fmt.Println(name)
		}
	}
}

func read() {
	in := bufio.NewReader(os.Stdin)
	for {
		line, err := in.ReadString(delim)
		if len(line) > 1 {
			recent(line[:len(line)-1], false)
		}
		if err != nil {
			if err != os.EOF {
				log.Println(err)
			}
			return
		}
	}
}

//Usage: %name %flags file*
func main() {
	log.SetFlags(0)
	flag.Parse()

	//default to files changed in the last day
	if *min == 0 && *hour == 0 && *day == 0 && *month == 0 && *year == 0 {
		*day = 1
	}
	Int("minutes", *min, 60)
	Int("hours", *hour, 24)
	Int("days", *day, 31)
	Int("months", *month, 12)
	if *year < 0 {
		log.Fatalln("year is invalid")
	}
	now := time.LocalTime()
	now.Minute -= *min
	now.Hour -= *hour
	now.Day -= *day
	now.Month -= *month
	now.Year -= *year
	now.Second = 0
	epoch = now.Seconds() / 1000
	if *z {
		delim = 0
	}

	if flag.NArg() == 0 {
		read()
	}
	for _, arg := range flag.Args() {
		recent(arg, true)
	}
	if !seen {
		os.Exit(1)
	}
}
